﻿using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WYD.Infrastructure.Attribute;
using WYD.Infrastructure.Controllers;
using WYD.Infrastructure.Enums;
using WYD.Infrastructure.WebExtensions;
using WYD.Model;
using WYD.ServiceCore.Filters;
using WYD.ServiceCore.Model;
using WYD.ServiceCore.Model.Dto;
using WYD.ServiceCore.Services.IService;

namespace WYD.Admin.WebApi.Controllers.System
{
    /// <summary>
    /// 数据字典信息
    /// </summary>
    [Route("system/dict/data")]
    [ApiExplorerSettings(GroupName = "sys")]
    public class SysDictDataController : BaseController
    {
        private readonly ISysDictDataService _sysDictDataService;
        private readonly ISysDictService _sysDictService;

        public SysDictDataController(ISysDictService sysDictService, ISysDictDataService sysDictDataService)
        {
            _sysDictService = sysDictService;
            _sysDictDataService = sysDictDataService;
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="dictData"></param>
        /// <param name="pagerInfo"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "system:dict:list")]
        [HttpGet("list")]
        public IActionResult List([FromQuery] SysDictData dictData, [FromQuery] PagerInfo pagerInfo)
        {
            var list = _sysDictDataService.SelectDictDataList(dictData, pagerInfo);

            if (dictData.DictType != null && dictData.DictType.StartsWith("sql_"))
            {
                var result = _sysDictService.SelectDictDataByCustomSql(dictData.DictType);

                list.Result.AddRange(result.Adapt<List<SysDictData>>());
                list.TotalNum += result.Count;
            }
            return SUCCESS(list);
        }

        /// <summary>
        /// 根据字典类型查询字典数据信息
        /// </summary>
        /// <param name="dictType"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("type/{dictType}")]
        public IActionResult DictType(string dictType)
        {
            return SUCCESS(_sysDictDataService.SelectDictDataByType(dictType));
        }

        /// <summary>
        /// 根据字典类型查询字典数据信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("types")]
        public IActionResult DictTypes([FromBody] List<SysdictDataParamDto> dto, [FromQuery] bool getAll = false)
        {
            // var list = _sysDictDataService.SelectDictDataByTypes(dto.Select(f => f.DictType).ToArray(), getAll);
            var dataVos = GetDicts(dto.Select(f => f.DictType).ToArray(), getAll);

            return SUCCESS(dataVos);
        }

        /// <summary>
        /// 移动端使用uniapp
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("dicts")]
        public async Task<IActionResult> GetDictTypes()
        {
            var data = await HttpContext.GetBodyAsync();
            return SUCCESS(GetDicts(JsonConvert.DeserializeObject<string[]>(data)));
        }
        
        private List<SysdictDataParamDto> GetDicts([FromBody] string[] dicts, bool getAll = false)
        {
            List<SysdictDataParamDto> dataVos = new();
            var list = _sysDictDataService.SelectDictDataByTypes(dicts, getAll);

            if (getAll)
            {
                foreach (var item in list)
                {
                    SysdictDataParamDto vo = new()
                    {
                        DictType = item.DictType,
                        List = list.FindAll(f => f.DictType == item.DictType)
                    };
                    dataVos.Add(vo);
                }
            }
            else
            {
                foreach (var dic in dicts)
                {
                    SysdictDataParamDto vo = new()
                    {
                        DictType = dic,
                        List = list.FindAll(f => f.DictType == dic)
                    };
                    if (dic.StartsWith("cus_") || dic.StartsWith("sql_"))
                    {
                        vo.List.AddRange(_sysDictService.SelectDictDataByCustomSql(dic));
                    }
                    dataVos.Add(vo);
                }
            }

            return dataVos;
        }

        /// <summary>
        /// 查询字典数据详细
        /// </summary>
        /// <param name="dictCode"></param>
        /// <returns></returns>
        [HttpGet("info/{dictCode}")]
        public IActionResult GetInfo(long dictCode)
        {
            return SUCCESS(_sysDictDataService.SelectDictDataById(dictCode));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "system:dict:add")]
        [Log(Title = "字典数据", BusinessType = BusinessType.INSERT)]
        [HttpPost()]
        public IActionResult Add([FromBody] SysDictData dict)
        {
            dict.CreateBy = HttpContext.GetUId();
            dict.CreateName = HttpContext.GetNickName();
            dict.CreateTime = DateTime.Now;
            return SUCCESS(_sysDictDataService.InsertDictData(dict));
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dict"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "system:dict:edit")]
        [Log(Title = "字典数据", BusinessType = BusinessType.UPDATE)]
        [HttpPut()]
        public IActionResult Edit([FromBody] SysDictData dict)
        {
            dict.UpdateBy = HttpContext.GetUId();
            dict.UpdateName = HttpContext.GetNickName();
            return SUCCESS(_sysDictDataService.UpdateDictData(dict));
        }

        /// <summary>
        /// 修改字典数据状态
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut("changeStatus")]
        [Log(Title = "修改字典数据状态", BusinessType = BusinessType.UPDATE)]
        [ActionPermissionFilter(Permission = "system:dict:edit")]
        public IActionResult ChangeStatus([FromBody] SysDictData dto)
        {
            int result = _sysDictDataService.UpdateStatus(dto);

            return ToResponse(result);
        }

        /// <summary>
        /// 删除字典类型
        /// </summary>
        /// <param name="dictCode"></param>
        /// <returns></returns>
        [ActionPermissionFilter(Permission = "system:dict:remove")]
        [Log(Title = "字典类型", BusinessType = BusinessType.DELETE)]
        [HttpDelete("{dictCode}")]
        public IActionResult Remove(string dictCode)
        {
            long[] dictCodes = Common.Tools.SpitLongArrary(dictCode);

            return SUCCESS(_sysDictDataService.DeleteDictDataByIds(dictCodes));
        }
    }
}
